package com.hn658.groupshare.common.validate.impl;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hn658.framework.logging.enums.LogCategory;
import com.hn658.framework.shared.utils.JsonMapper;
import com.hn658.groupshare.common.utils.StreamIOHelper;
import com.hn658.groupshare.common.validate.IValidateIpManager;
import com.hn658.groupshare.common.validate.dto.IpLookupResponse;
import com.hn658.groupshare.common.validate.store.IpStore;
import com.hn658.groupshare.config.service.IGroupShareConfig;

@Component
public class ValidateIpManagerImpl implements IValidateIpManager, InitializingBean{
    /**
     * 日志记录器
     */
    protected final Logger logger = LoggerFactory.getLogger(ValidateIpManagerImpl.class);

    /**
     * 下载多线程管理器
     */
    private static PoolingClientConnectionManager connMger;

    /**
     * 下载参数
     */
    private static HttpParams connParams;
    
    private Set<String> passAddress = new HashSet<String>();
    
    private Set<String> passIps = new HashSet<String>();

    @Autowired
	private IGroupShareConfig config;
    
    @Autowired
    private IpStore ipStore;
	
	private JsonMapper jsonMapper =JsonMapper.nonDefaultMapper();

	@Override
	public void afterPropertiesSet() throws Exception {
		// 初始化下载线程池
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(
                new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(
                new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

        connMger = new PoolingClientConnectionManager(schemeRegistry);
        connMger.setDefaultMaxPerRoute(config.getHttpClientMaxRouteConnection());
        connMger.setMaxTotal(config.getHttpClientMaxConnection());

        // 初始化下载参数
        connParams = new BasicHttpParams();
        connParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getHttpClientTimeout());
        connParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, config.getHttpClientSotimeout());
        connParams.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,config.getHttpClientSocketBuffersize());
        
        String[] addressArray = config.getPassAddress().split(",");
        for(String address : addressArray){
        	passAddress.add(address);
        }
        
        String[] ipArray = config.getPassIp().split(",");
        for(String ip : ipArray){
        	passIps.add(ip);
        }
	}

    public HttpClient getHttpClient() {
        DefaultHttpClient client = new DefaultHttpClient(connMger, connParams);
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(config.getHttpClientMaxRetry(), false));
        return client;
    }

	private String queryIpAddress(String ip) {
		HttpResponse httpResponse;
		try {
			String requestUri = String.format(config.getSinaValidateIpUrl(), ip);
			httpResponse = getHttpClient().execute(new HttpGet(requestUri));
			String respoString = StreamIOHelper.inputStreamToStr(httpResponse.getEntity().getContent(), "GB2312");
			IpLookupResponse response = this.jsonMapper.fromJson(respoString, IpLookupResponse.class);
			if(response!=null){
				return response.getCity();
			}
		} catch (Exception e) {
			logger.error("查询IP所属地异常:{}", ExceptionUtils.getStackTrace(e));
		}
		return null;
	}
    
    @Override
	public Boolean validate(String ip) {
    	
    	//未开启ip过滤，则所有ip可访问
		if(StringUtils.isBlank( config.getIsOpenIp()) ||
				!"open".equals(config.getIsOpenIp()) ){
			logger.debug(LogCategory.SYSTEM, "ip validator not open.");
			return true;
		}
    	
    	if(passIps.contains(ip)){
    		logger.debug("请求IP在白名单内:{}", ip);
    		return true;
    	}
    	String address = ipStore.getIpAndAddress(ip);
    	if(address==null){
    		address = this.queryIpAddress(ip);
    		if(StringUtils.isEmpty(address)){
    			address = "null";
    		}
    		logger.debug("请求IP:{}，Ip所属地:{}", new Object[]{ip, address});
    		ipStore.saveIpAndAddress(ip, address);
    	}
		return passAddress.contains(address);
	}

}